package com.spirit.concurrency.visibility;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author eric - 好好学习，天天向上！
 * @date 2022/2/20
 * @description 可见性问题
 */
public class Visibility {
    private static final Logger logger = LoggerFactory.getLogger(Visibility.class);
    private static long count = 0;

    private void add10k() {
        int idx = 0;
        while (idx++ <= 1000000) {
            count += 1;
        }
    }


    public static long calc() {
        final Visibility visibility = new Visibility();
        // 创建两个线程来操作 add
        Thread t1 = new Thread(() -> {
            visibility.add10k();
        });
        Thread t2 = new Thread(() -> {
            visibility.add10k();
        });

        t1.start();
        t2.start();

        // 等待两个线程结束
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            logger.error("线程被打断了。。。");
        }

        return count;
    }

    public static void main(String[] args) {
        logger.info("计算结果为:" + calc());
    }

}
